<?php
/**
 * Created by PhpStorm.
 * User: 杨胜飞
 * Date: 2017\8\26 0026
 * Time: 15:29
 */

namespace app\common\model;



use app\administrative\controller\Contractinfo;
use think\db;
use app\common\model\Customer;
use think\Exception;
use think\Model;

/**
 * Class WorkOrder
 * @package app\common\model
 *     工单表  模型
 */
class WorkOrder extends Model
{

    /**
     * @param $data
     * @return bool|false|int
     *    添加数据
     */
    public function add($data)
    {
        // 添加数据 过滤表中不存在的字段 工单表
        $this->data($data);
        $result = $this->allowField(true)->save();
        // 判断结果 并返回
        if ($result !== 1) {
            return false;
        }
        return $result;
    }

    /**
     * @param $id
     * @return $this|bool
     *         根据主键ID 完成一次逻辑删除 或 恢复
     */
    public function remove($id,$is_delete)  // 工单id ，is_delete删除还是恢复
    {
        // 根据主键ID 完成一次逻辑删除
        $result = $this->where('work_order_id',$id)->update(['is_delete' => $is_delete]);
        // 判断结果并返回
        if ($result !== 1) {
            return false;
        }
        return $result;
    }

    /**
     * @param $where  ->  条件  ['key' => 'value']
     * @param $data   ->  数据  ['key' => 'value','key' => 'value']
     * @return $this|bool
     *          根据条件 $where 完成一次数据修改
     */
    public function edit($where,$data)
    {
        // 根据条件 $where 完成一次数据修改
        $result = $this->where($where)->update($data);
        // 判断数据 并返回
        if ($result !== 1) {
            return false;
        }
        return $result;
    }

    /**
     * @param $where   ->  条件   ['key' => 'value']
     * @return array|bool|false|\PDOStatement|string|Model
     *       根据条件 $where 查询单条数据
     */
    public function getOne($where)
    {
        // 根据条件 $where 查询单条数据
        $userInfo = $this->where($where)->find();
        // 判断结果 并返回
        if ($userInfo == false) {
            return false;
        }
        return $userInfo;
    }

    /**
     * @param $where
     * @return int|string
     *      查询工程人员已完成工单
     */
    public function workCount($where)
    {
        $count = $this->where($where)->count();
        return $count;
    }

    /**
     * @param $where   ->  条件   ['key' => 'value']
     * @return array|bool|false|\PDOStatement|string|Model
     *       根据条件 $where 查询单条数据
     */
    public function getWEquipmentOne($where,$field='*')
    {
        // 根据条件 $where 查询单条数据
        $userInfo = $this->where($where)
            ->alias('wo')
            ->join('rq_work_equipment we','wo.work_order_id = we.work_order_id')
            ->field($field)
            ->find();
        // 判断结果 并返回
        if ($userInfo == false) {
            return false;
        }
        return $userInfo;
    }



    /**
     * @return bool|false|\PDOStatement|string|\think\Collection
     *      查询 工单表 所有数据
     */
    public function getList($where = '', $field = '*')
    {
        // 查询 工单表 所有 未被逻辑删除 数据
        $userInfo = $this->where(['is_delete' => 0])->where($where)->field($field)->select();
        // 判断结果 并返回
        if ($userInfo == false) {
            return false;
        }
        return $userInfo;
    }

    /**
     * @param $id   ->  客户id
     * @return false|\PDOStatement|string|\think\Collection
     *        获取 工单 修改回显数据
     */
    public function getEdit($id)
    {

        // 连表查询，获取工单管理列表页
        $data = Db::table('rq_work_order') //  工单表
        ->alias('a')
            ->join('rq_customer b', 'b.user_id = a.user_id') // 客户表 对应 工单表
            ->join('rq_contract c', 'c.contract_id = a.contract_id') // 合同表 对应 工单表
            ->join('rq_operation_info d', 'd.o_id = a.operation_id') // 运营中心表 对应 工单表
            ->join('rq_engineers e', 'e.engineers_id = a.repair_id') // 工程人员表 对应 工单表
            ->field('a.order_number,b.username,c.contract_no,d.company_name,b.area,
                               a.business_id,a.combo_money,a.work_order_status,a.order_time,
                               e.engineers_phone,c.moving_machine_number,a.work_order_id,
                               b.user_id,c.contract_id,d.o_id,e.engineers_id')// 工单号   户名     合同编号    运营中心   所属区域   工单类型  金额  处理状态   下单时间   工程部    移机次数 工单id
            ->where('a.work_order_id',$id)
            ->select();

        return $data;
    }

    /**
     * @param $data
     *       处理 工单信息修改
     */
    public function getModify($data)
    {

        // 修改工单表 数据
        $workOrder = $this->allowField(true)->save($data,['user_id' => $data['user_id']]);


        // 修改客户表 实例化客户表模型 Customer
        $customerModel = new Customer();
        // 生成条件
        $map = [];
        $map['user_id'] = $data['user_id'];
        // 修改数据
        $customerData['username'] = $data['username'];
        $customerData['area'] = $data['area'];
        // 调用 updateOne 方法 完成数据修改
        $customer = $customerModel->updateOne($map,$customerData);


        // 修改合同表 实例化合同表模型
        $contractModel = new Contract();
        // 生成条件
        $contractMap = [];
        $contractMap['user_id'] = $data['user_id'];
        // 修改数据  合同编号  移机次数
        $contractData['contract_no'] = $data['contract_no'];
        $contractData['moving_machine_number'] = $data['moving_machine_number'];
        // 调用 updateOne 方法 完成数据修改
        $contractModel->updateOne($contractMap,$contractData);


        // 修改工程人员 实例化
        $engineersModel = new Engineers();
        // 生成条件
        $engineersMap = [];
        $engineersMap['engineers_id'] = $data['repair_id'];
        // 修改数据  合同编号  移机次数
        $engineersData['engineers_name'] = $data['engineers_name'];
        // 调用 edit 方法 完成数据修改
        $engineersModel->edit($engineersMap,$engineersData);

    }

    /**
     * @author ligang   修改参数$join可以为空，增加$whereOR,$whereTime参数
     * @return bool|int|string
     *      获取工单管理 数据的 总条数
     *
     */
    public function getCount($where, $dbName, $join = '',$whereOR = [],$whereTimeFiled='',$whereTimeOp = '')
    {
        if (empty($join)){
            if (empty($whereTimeFiled) && empty($whereTimeOp)){
                $count = Db::table($dbName)          // 主表
                ->where($where)             // 条件
                ->whereOr($whereOR)
                ->count();                  // 查询数据数量

            }else{
                $count = Db::table($dbName)          // 主表
                ->where($where)             // 条件
                ->whereOr($whereOR)
                ->whereTime($whereTimeFiled,$whereTimeOp)
                ->count();                  // 查询数据数量
            }
//            dump(Db::table($dbName)->getLastSql());
        }else{
            //  获取工单管理页面的总的条数
            $count = Db::table($dbName)          // 主表
            ->alias('a')                   // 主表别名
            ->join($join)                        // 需要关联的表
            ->where($where)                      // 条件
            ->count();                           // 查询数据数量
        }
//        dump(Db::table($dbName)->getLastSql());
        // 返回结果
        return $count;

    }

    /*
     * 计算工单金额
     * @author ligang
     * @param array     $where          条件
     * @param string    $dbName         表名（含前缀）
     * @param string    $field          统计的字段名
     * @param array     $join           关联条件
     * @param string    $whereTimeFiled 时间字段
     * @param string    $whereTimeOp    时间规则
     * @return  int
     */
    public function countWorkOrderMoney($where,$dbName,$field,$join=[],$whereTimeFiled='',$whereTimeOp = '')
    {
        if (empty($join)){
            if (empty($whereTimeFiled) && empty($whereTimeOp)){
                $result = Db::table($dbName)->where($where)->sum($field);
            }else{
                $result = Db::table($dbName)->where($where)->whereTime($whereTimeFiled,$whereTimeOp)->sum($field);

            }
        }else{
            if (empty($whereTimeFiled) && empty($whereTimeOp)){
                $result = Db::table($dbName)->where($where)->join($join)->sum($field);
            }else{
                $result = Db::table($dbName)->where($where)->whereTime($whereTimeFiled,$whereTimeOp)->join($join)->sum($field);
            }
        }
//        dump(Db::table($dbName)->getLastSql());
        return $result;
    }

    /**
     * @param int $nowPage
     * @param string $limits
     * @param int $id
     * @param string $keywords
     * @return false|\PDOStatement|string|\think\Collection
     *         获取 所有工单列表页 数据
     */
    public function getAll($field = '*', $where = [], $nowPage = '', $limits = '', $dbName='', $join='', $order = 'a.order_time desc')
    {

        // 连表查询，获取工单管理列表页
        $data = Db::table($dbName)          // 主表
                ->alias('a')          // 主表别名
                ->join($join)               // 需要关联的表
                ->field($field)             // 需要查询的字段
                ->where($where)             // 条件
                ->order($order)             // 排序方式
                ->page($nowPage,$limits)    // 开始位置，多少数据
                ->select();
//        echo Db::table($dbName)->getLastSql();exit;
        // 返回结果
        return $data;

    }

    /**
     * @param int $id
     * @return array
     *        获取工单详情 数据
     */
    public function getDetail($id = 0) // 工单id
    {

        // 获取工单详情  基本信息
        $basicData = Db::table('rq_work_order') // 工单表
                    ->alias('a')
                    ->join('rq_customer b', 'b.user_id = a.user_id','LEFT') // 客户表 对应 工单表
                    ->field('b.username,b.telphone,b.add_time,b.account_status,b.remark,b.birthday,b.user_address') // 基本信息中账号就是客户联系电话
                    ->where('a.work_order_id',$id) // 对应工单id号
                    ->select();

        // 获取工单详情  工单信息
        $workData = Db::table('rq_work_order')  // 工单表
                    ->alias('a')
                    ->join('rq_engineers b', 'b.engineers_id = a.repair_id','LEFT')             // 工程人员表 对应 工单表
                    ->join('rq_contract j', 'j.contract_id = a.contract_id','LEFT')             // 合同表 对应 工单表
                    ->join('rq_administrative_info h', 'h.a_id = a.administrative_id','LEFT')   // 行政中心表 对应 工单表
                    ->join('rq_operation_info r', 'r.o_id = a.operation_id','LEFT')             // 运营中心表 对应 工单表
                    ->field('a.order_number,j.contract_no,a.business_id,r.company_name as y_name,h.company_name,
                                   a.work_order_status,b.engineers_name,b.engineers_phone,a.province,a.city,a.area,a.service_address,
                                   a.combo_money,a.move_address,a.contacts,a.contact_number,a.remarks,a.move_province,
                                   a.move_city,a.move_area,a.move_province_code,a.move_city_code,a.move_area_code,a.work_order_id')
                    ->where('a.work_order_id',$id)
                    ->select();
//        dump($workData);echo "<hr>";


        // 实例化工单设备关联表
        $workEquipmentModel = new WorkEquipment();
        if (!empty($workData)) {
            $workEquipmentWhere['work_order_id'] = $workData[0]['work_order_id'];
            // 获取合同设备关联表ID
            $workEquipmentData = $workEquipmentModel->getAll($workEquipmentWhere);
        }
//        dump(json_decode(json_encode($workEquipmentData),true));die();
        if (!empty($workEquipmentData)) {
            foreach ($workEquipmentData as $k => $v)
            {
                // 实例化合同设备关联表
                $contractEquipmentModel = new ContractEquipment();
                $wheres['id'] = $v['contract_equipment_id'];
                // 获取设备编号
                $equipmentNumber[] = $contractEquipmentModel->getAll($wheres);

            }
        }
        if (!empty($equipmentNumber)) {
            // 声明一个空数组用来装设备信息
            $equipmentNumbers = [];
            foreach ($equipmentNumber as $k => $v)
            {
                foreach ($v as $key => $val)
                {
                    $equipmentNumbers[] = $val;
                }
            }
        }else{
            $equipmentNumbers = '';
        }

//        dump(json_decode(json_encode($equipmentNumbers),true));die();

        // 实例化工单配件关联表
        $workpartsModel = new WorkParts();
        $workpartswhere['work_order_id'] = $id;
        // 获取配件id
        $partsId = $workpartsModel->getAll($workpartswhere);
        // 实例化配件表
        $partsModel = new Parts();
        // 判断是否为空
        if (!empty($partsId)) {
            // 获取配件信息
            foreach ($partsId as $k => $v)
            {
                $partswhere['parts_id'] = $v['parts_id'];
                $partswhere['is_delete'] = 0;
                $partsData[] = $partsModel->selectOne($partswhere);
            }
            // 将配件信息跟配件数量合并
            foreach ($partsData as $k => $v)
            {
                $partsData[$k]['parts_number'] = $partsId[$k]['parts_number'];
            }
        }
        // 如果没有就为空
        if (empty($partsData)) {
            $partsData = '';
        }

        // 获取工单详情  工单轨迹
        $userData = Db::name('work_order_log') // 工单日志表
                    ->field('create_work_time,operating_time,remarks')
                    ->where('work_order_id',$id)
                    ->order('operating_time desc')
                    ->limit(5)
                    ->select();

        // 拼接返回
        $arr = [
            '0' => $basicData,
            '1' => $workData,
            '2' => $userData,
            '3' => $equipmentNumbers,
            '4' => $partsData
        ];

        return $arr;

    }

    /**
     * @param string $id
     * @param string $dbName
     * @param string $field
     * @param string $order
     * @param int $limits
     *          获取工单轨迹
     */
    public function getLast($where = [], $limits = 5, $dbName = 'work_order_log', $field = 'create_work_time,operating_time,remarks', $order = 'operating_time desc')
    {
        // 获取工单详情  工单轨迹
        $userData = Db::name($dbName) // 工单日志表
                    ->field($field)
                    ->where($where)
                    ->order($order)
                    ->limit($limits)
                    ->select();

        return $userData;
    }

    /**
     * @param $data
     * @return $this
     *      ajax  异步修改 工单 处理状态
     */
    public function editStatus($data, $u_id, $username, $company_name)
    {
        // 开启事务
        Db::startTrans();
        try{
            // 拼接 条件
            $workId = ['work_order_id' => $data['work_order_id']];

            // 拼接 数据
            if ($data['work_order_status'] < 7) {
                $statusType = ['work_order_status' => $data['work_order_status'],'update_time' => time(),'repair_id' => 0];
            }else{
                $statusType = ['work_order_status' => $data['work_order_status'],'update_time' => time()];
            }

            // 获取工单操作状态
            $work_order_status = config('work_order_status');

            // 根据工单ID，获取工单数据
            $workData = $this->where($workId)->find();

            // 当业务类型为移机时，当这条工单走完时，合同设备关联表的设备地址，改为移机地址
            if ($workData['business_id'] == 5 ||  $workData['business_id'] == 9 || $workData['business_id'] == 10) {
                if ($data['work_order_status'] == 12) {
                    // 实例化合同设备表模型
                    $contractEquipmentModel = new ContractEquipment();
                    $cewhere['contract_id'] = $workData['contract_id'];
                    $cedata['equipments_address'] = $workData['move_address'];
                    $result = $contractEquipmentModel->edit($cewhere,$cedata);
                }
            }
            // 当业务类型为拆机时，当这条工单做完时，解绑设备
            if ($workData['business_id'] == 4) {
                if ($data['work_order_status'] == 12) {
                    // 实例化工单设备表模型 获取合同设备ID
                    $workEquipmentModel = new WorkEquipment();
                    $wewhere['work_order_id'] = $data['work_order_id'];
                    $workEquipmentData = $workEquipmentModel->getOne($wewhere);
                    // 调用方法进行解绑
                    $Contractinfo = new Contractinfo();
                    $result = $Contractinfo->unBindEquipments($workEquipmentData['contract_equipment_id']);
                }
            }
            // 根据条件 $where 完成一次数据修改
            $workresult = $this->where($workId)->update($statusType);

            // 增加工单日志表记录
            $workLogData = [];
            $workLogData['work_order_id'] = $data['work_order_id'];            // 工单id
            $workLogData['operating_time'] = time();                           // 操作时间
            $workLogData['create_work_time'] = time();                         // 添加时间
            $workLogData['do_id'] = $u_id;                                     // 操作人id
            $workLogData['operating_type'] = 3;                                // 3为其他操作
            $workLogData['operating_status'] = $data['work_order_status'];     // 操作状态
            $workLogData['remarks'] = '【'.$company_name.'】管理员【'.$username.'】【管理员ID为:'.$u_id.'】修改工单状态为：【'.$work_order_status[$data['work_order_status']].'】工单号为:【'.$workData['order_number'].'】';  // 备注
            // 实例化工单日志表
            $workLogModel = new WorkOrderLog();
            // 调用add方法增加工单日志数据
            $logresult = $workLogModel->add($workLogData);

            // 判断是否有备注，没有则不增加数据
            if (!empty($data['remarks'])) {
                // 增加工单备注关联表
                $workRemarksData = [];
                $workRemarksData['u_id'] = $u_id;                               // 操作人id
                $workRemarksData['username'] = $username;                       // 操作人姓名
                $workRemarksData['operating_time'] = time();                    // 操作时间
                $workRemarksData['work_order_id'] = $data['work_order_id'];     // 工单id
                $workRemarksData['remarks'] = $data['remarks'];                 // 备注信息
                // 实例化工单备注关联表
                $workRemarksModel = new WorkOrderRemarks();
                // 调用add方法增加工单备注关联表数据
                $remarkresult = $workRemarksModel->add($workRemarksData);
            }
            // 提交事务
            Db::commit();
            $rel = true;
        }catch (\Exception $e){
            // 事务回滚
            Db::rollback();
            // dump($e->getMessage());
            $rel = false;
        }

        return $rel;

    }


    /**
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     *         根据工程人员id  查询他名下所有已完成的工单  数量   工程人员板块
     */
    public function getCompleted($id) // 工程人员id
    {

        // 拼接条件
        $where = ['repair_id' => $id];
        // 获取已完成的工单
        $count = $this->where($where)
                      ->where('work_order_status',['>',8],['<',13])
                      ->count();
        // 返回
        return $count;
    }

    /**
     * @param $id
     * @return int|string
     *       根据工程人员id  查询他名下所有未完成的工单数  数量   工程人员板块
     */
    public function getUncompleted($id) // 工程人员id
    {

        // 拼接条件
        $where = ['repair_id' => $id];
        // 获取未完成的工单
        $count = $this->where($where)
                      ->where('work_order_status',8)
                      ->count();
        // 返回
        return $count;
    }

    /**
     * @param int $id
     * @return false|\PDOStatement|string|\think\Collection
     *          根据工程人员id  查询他名下所有已完成或待完成的工单数据    工程人员板块
     */
    public function getCompleteds($id = 0,$nowPage='',$limits='',$searchObj='',$startStatus = '',$endStatus = '')
    {
        // 判断用户有没有输开始日期
        if (empty($searchObj['startTime'])) {
            $startTime = '2005-01-01';
        }else{
            $startTime = $searchObj['startTime'];
        }

        // 判断用户有没有输结束日期
        if (empty($searchObj['endTime'])) {
            $endTime = date('Y-m-d',time());
        }else{
            $endTime = $searchObj['endTime'];
        }
        // 判断有没有输入工单号
        if (empty($searchObj['order_number'])) {
            $order_number = '';
        }else{
            $order_number = $searchObj['order_number'];
        }
        // 判断有没有输入用户名
        if (empty($searchObj['username'])) {
            $username = '';
        }else{
            $username = $searchObj['username'];
        }
        // 判断有没有输入合同编号
        if (empty($searchObj['contract_no'])) {
            $contract_no = '';
        }else{
            $contract_no = $searchObj['contract_no'];
        }
        // 判断有没有输入工单类型
        if (empty($searchObj['type'])) {
            $type = '';
        }else{
            $type = $searchObj['type'];
        }

        // 判断用户有没有输地区搜索  省 ，
        if (empty($searchObj['province'])) {
            $province = '';
        }else{
            $province = ['d.province_code' => $searchObj['province']];
        }
        // 判断用户有没有输地区搜索 市 ，
        if (empty($searchObj['city'])) {
            $city = '';
        }else{
            $city = ['d.city_code' => $searchObj['city']];
        }
        // 判断用户有没有输地区搜索 区，
        if (empty($searchObj['area'])) {
            $area = '';
        }else{
            $area = ['d.area_code' => $searchObj['area']];
        }
        // 将日期转换为时间戳，用于条件查询
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);

        $data = Db::table('rq_engineers')  // 工程人员表
        ->alias('a')
            ->join('rq_work_order b','b.repair_id = a.engineers_id')  // 工单表 对应 工程人员表
            ->join('rq_contract c','c.contract_id = b.contract_id')  // 合同表  对应 工单表
            ->join('rq_customer d','d.user_id = b.user_id')         //  客户表  对应 工单表
            ->field('b.order_number,d.username,c.contract_no,d.area,b.business_id,d.user_address,b.combo_money,
                                   b.order_time,c.moving_machine_number,a.engineers_id,b.work_order_id')
            ->where('work_order_status',['>',$startStatus],['<',$endStatus])
            ->where('b.order_number','like',"%$order_number%")
            ->where('d.username','like',"%$username%")
            ->where('c.contract_no','like',"%$contract_no%")
            ->where('b.business_id','like',"%$type%")
            ->where($province)
            ->where($city)
            ->where($area)
            ->where('b.order_time',['>',$startTime],['<',$endTime],'and')
            ->where('a.engineers_id',$id)
            ->page($nowPage,$limits)
            ->order('b.order_time desc')
            ->select();
        return $data;

    }

    /**
     * @param $id
     * @return int|string
     *         根据工程人员id ，获取他已完成的工单的总数   工程人员板块
     */
    public function getCompletedCount($id,$searchObj = '',$startStatus = '',$endStatus = '')
    {
        // 判断用户有没有输开始日期
        if (empty($searchObj['startTime'])) {
            $startTime = '2005-01-01';
        }else{
            $startTime = $searchObj['startTime'];
        }

        // 判断用户有没有输结束日期
        if (empty($searchObj['endTime'])) {
            $endTime = date('Y-m-d',time());
        }else{
            $endTime = $searchObj['endTime'];
        }
        // 判断有没有输入工单号
        if (empty($searchObj['order_number'])) {
            $order_number = '';
        }else{
            $order_number = $searchObj['order_number'];
        }
        // 判断有没有输入用户名
        if (empty($searchObj['username'])) {
            $username = '';
        }else{
            $username = $searchObj['username'];
        }
        // 判断有没有输入合同编号
        if (empty($searchObj['contract_no'])) {
            $contract_no = '';
        }else{
            $contract_no = $searchObj['contract_no'];
        }
        // 判断有没有输入工单类型
        if (empty($searchObj['type'])) {
            $type = '';
        }else{
            $type = $searchObj['type'];
        }

        // 判断用户有没有输地区搜索  省 ，
        if (empty($searchObj['province'])) {
            $province = '';
        }else{
            $province = ['d.province_code' => $searchObj['province']];
        }
        // 判断用户有没有输地区搜索 市 ，
        if (empty($searchObj['city'])) {
            $city = '';
        }else{
            $city = ['d.city_code' => $searchObj['city']];
        }
        // 判断用户有没有输地区搜索 区，
        if (empty($searchObj['area'])) {
            $area = '';
        }else{
            $area = ['d.area_code' => $searchObj['area']];
        }

        // 将日期转换为时间戳，用于条件查询
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);

        $data = Db::table('rq_engineers')  // 工程人员表
        ->alias('a')
            ->join('rq_work_order b','b.repair_id = a.engineers_id')  // 工单表 对应 工程人员表
            ->join('rq_contract c','c.contract_id = b.contract_id')  // 合同表  对应 工单表
            ->join('rq_customer d','d.user_id = b.user_id')         //  客户表  对应 工单表
            ->field('b.order_number,d.username,c.contract_no,d.area,b.business_id,d.user_address,b.combo_money,
                                           b.order_time,c.moving_machine_number,a.engineers_id')
            ->where('work_order_status',['>',$startStatus],['<',$endStatus])
            ->where('b.order_number','like',"%$order_number%")
            ->where('d.username','like',"%$username%")
            ->where('c.contract_no','like',"%$contract_no%")
            ->where('b.business_id','like',"%$type%")
            ->where($province)
            ->where($city)
            ->where($area)
            ->where('b.order_time',['>',$startTime],['<',$endTime],'and')
            ->where('a.engineers_id',$id)
            ->count();

        return $data;
    }


    public function getAllByWhere($map=[],$nowPage,$limits){
        $data = Db::table('rq_engineers')  // 工程人员表
        ->alias('a')
            ->join('rq_work_order b','b.repair_id = a.engineers_id')  // 工单表 对应 工程人员表
            ->join('rq_contract c','c.contract_id = b.contract_id','left')  // 合同表  对应 工单表
            ->join('rq_customer d','d.user_id = b.user_id')         //  客户表  对应 工单表
            ->field('b.order_number,b.province,b.city,b.area,b.service_address,c.contract_no,d.area,b.business_id,d.user_address,b.combo_money,
                                   b.order_time,c.moving_machine_number,a.engineers_id,b.work_order_id,b.contact_number,b.contacts')
            ->where($map)
            ->page($nowPage,$limits)
            ->order('b.order_time desc')
            ->select();

        return $data;
    }

    /**
     * @param $data
     * @param $username
     * @return bool
     *            新增一条工单数据，获取他的id，同时增加一条工单日志数据,同时增加对应业务类型记录
     */
    public function insertId($data, $username, $u_id, $contract_equipment_id, $company_name)
    {
//        dump($data);die();
        // 开启事务
        Db::startTrans();
        try{
            // 增加一条工单数据 获取他的id
            $work_id = $this->allowField(true)->insertGetId($data);

            // 判断是否为添加新装
            if ($data['business_id'] == 3) {
                // 判断是否有合同编号
                if (!empty($data['contract_id'])) {
                    // 实例化合同设备关联表,查询合同下面所有设备
                    $ctEqModel = new Contract();
                    $ctEqWhere['contract_id'] = $data['contract_id'];
                    $ctEqData = $ctEqModel->getEquipmentAll($ctEqWhere);
                    // 添加设备
                    foreach ($ctEqData as $k => $v)
                    {
                        // 实例化工单设备关联表
                        $wkEqModel = new WorkEquipment();
                        $wkEqData['work_order_id'] = $work_id;
                        $wkEqData['contract_equipment_id'] = $v['id'];
                        $wkEqRel = $wkEqModel->add($wkEqData);
                    }
                }
            }else{
                // 工单设备关联表中插入一条数据
                $work_equipment = [
                    'work_order_id'=>$work_id,
                    'contract_equipment_id'=>$contract_equipment_id
                ];
                Db::name('work_equipment')->insertGetId($work_equipment);
            }
//            echo 11;die();
            // 获取工单类型
            $workType = [1 => '续费',2 => '换芯',3 => '新装',4 => '拆机',5 => '移机',6 => '维修',7 => '续费+维修',8 => '换芯+维修',9 => '移机拆',10 => '移机装'];

            // 声明一个空数组用来装工单日志表数据
            $workDataLog=[];
            $workDataLog['work_order_id'] = $work_id;     // 工单id
            $workDataLog['create_work_time'] = time();    // 订单创建时间
            $workDataLog['operating_time'] = time();      // 操作时间
            $workDataLog['operating_type'] = 0;           // 操作类型  0为前台确认
            $workDataLog['operating_status'] = 1;         // 操作状态为1  已处理
            $workDataLog['do_id'] = $u_id;                // 操作人id
            $workDataLog['remarks'] = '【'.$company_name.'】管理员【'.$username.'】【管理员ID为:'.$u_id.'】添加工单类型【'.$workType[$data['business_id']].'】工单号为【'.$data['order_number'].'】';  // 备注信息
            // 实例化工单日志表
            $workLogModel = new WorkOrderLog();
            // 调用add方法增加工单日志数据
            $log = $workLogModel->add($workDataLog);

            // 业务类型记录表
            $record = [];
            $record['work_order_id'] = $work_id;                 // 工单id
            $record['user_id'] = $data['user_id'];               // 客户id
            $record['repair_id'] = 0;                            // 新增工单没有工程人员
            $record['contract_id'] = $data['contract_id'];       // 合同ID
            $record['equipment_id'] = $contract_equipment_id;    // 合同设备关联id
            $record['remarks'] = '管理员【'.$username.'】【管理员ID为:'.$u_id.'】添加工单类型【'.$workType[$data['business_id']].'】工单号为【'.$data['order_number'].'】'; // 备注信息

            // 根据新增工单业务类型增加对应记录表数据
            // 表示增加续费工单
            if ($data['business_id'] == 1) {
                $record['renew_record_time'] = time();
                $renewModel = new RenewRecord();
                $recordData = $renewModel->insertOne($record);
            }
            // 表示增加换芯工单
            if ($data['business_id'] == 2){
                $record['for_core_record_time'] = time();
                $forcorerecordModel = new ForCoreRecord();
                $recordData = $forcorerecordModel->insertOne($record);
            }
            // 表示增加新装工单
            if ($data['business_id'] == 3){
                $record['new_record_time'] = time();
                $newrecordModel = new NewRecord();
                $recordData = $newrecordModel->add($record);
            }
            // 表示增加拆机工单
            if ($data['business_id'] == 4){
                $record['disassemble_record_time'] = time();
                $disassembleModel = new DisassembleRecord();
                $recordData = $disassembleModel->add($record);
            }
            // 表示增移机工单
            if ($data['business_id'] == 5){
                $record['shift_recordd_time'] = time();
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->insertOne($record);
            }
            // 表示增移机拆工单
            if ($data['business_id'] == 9){
                $record['shift_recordd_time'] = time();
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->insertOne($record);
            }
            // 表示增移机装工单
            if ($data['business_id'] == 10){
                $record['shift_recordd_time'] = time();
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->insertOne($record);
            }
            // 表示维修工单
            if ($data['business_id'] == 6){
                $record['repair_record_time'] = time();
                $repairModel = new RepairRecord();
                $recordData = $repairModel->add($record);
            }
            // 表示增续费+维修工单
            if ($data['business_id'] == 7){
                $record['renew_repair_record_time'] = time();
                $renewrepairModel = new RenewRepairRecord();
                $recordData = $renewrepairModel->add($record);
            }
            // 表示增换芯+维修工单
            if ($data['business_id'] == 8){
                $record['for_core_repair_record_time'] = time();
                $forcorerepairModel = new ForCoreRepairRecord();
                $recordData = $forcorerepairModel->insertOne($record);
            }

            // 增加工单备注关联表
            $workRemarksData = [];
            $workRemarksData['u_id'] = $u_id;                                                               // 操作人id
            $workRemarksData['username'] = $username;                                                       // 操作人姓名
            $workRemarksData['operating_time'] = time();                                                    // 操作时间
            $workRemarksData['work_order_id'] = $work_id;                                                   // 工单id
            $workRemarksData['remarks'] = $data['remarks'];                                                 // 备注信息
            // 实例化工单备注关联表
            $workRemarksModel = new WorkOrderRemarks();
            // 调用add方法增加工单备注关联表数据
            $remarksData = $workRemarksModel->add($workRemarksData);

            // 提交事务
            Db::commit();
            $res = true;
        }catch (\Exception $e){
            echo $e;
            // 事务回滚
            Db::rollback();
            $res = false;
        }
        // 返回结果
        return $res;

    }

    /**
     * @param $where
     * @param $editData
     * @param $u_id
     * @param $engineers_name
     * @param $username
     * @return bool
     *          工单指派工程人员操作
     */
    public function workassign($where, $editData, $u_id, $engineers_name, $username, $company_name)
    {
        // 开启事务
        Db::startTrans();
        try{
            // 根据工单ID获取工单号
            $workData = $this->where($where)->find();

            // 根据条件 $where 完成一次数据修改
            $result = $this->where($where)->update($editData);

            // 增加工单日志表记录
            $workLogData = [];
            $workLogData['work_order_id'] = $where['work_order_id'];     // 工单id
            $workLogData['operating_time'] = time();                     // 操作时间
            $workLogData['create_work_time'] = time();                   // 添加时间
            $workLogData['do_id'] = $u_id;                               // 操作人id
            $workLogData['e_id'] = $editData['repair_id'];               // 工程人员id
            $workLogData['operating_type'] = 1;                          // 1为工程部确认
            $workLogData['operating_status'] = 5;                        // 5为指派
            $workLogData['remarks'] = '【'.$company_name.'】管理员【'.$username.'】【管理员ID为:'.$u_id.'】指派工单给工程人员：【'.$engineers_name.'】工单号为:【'.$workData['order_number'].'】';  // 备注
            // 实例化工单日志表
            $workLogModel = new WorkOrderLog();
            // 调用add方法增加工单日志数据
            $workLogModel->add($workLogData);

            // 获取当前工单的信息
            $workwhere['work_order_id'] = $where['work_order_id'];
            $data = $this->getOne($workwhere);

            // 当指派工程人员是 修改 业务类型记录表
            $recordwhere['work_order_id'] = $where['work_order_id'];        // 工单id
            $record['repair_id'] = $editData['repair_id'];                  // 工程人员ID

            // 根据新增工单业务类型增加对应记录表数据
            // 表示增加续费工单
            if ($data['business_id'] == 1) {
                $renewModel = new RenewRecord();
                $recordData = $renewModel->modifyOne($recordwhere,$record);
            }
            // 表示换芯工单
            if ($data['business_id'] == 2){
                $forcorerecordModel = new ForCoreRecord();
                $recordData = $forcorerecordModel->modifyOne($recordwhere,$record);
            }
            // 表示新装工单
            if ($data['business_id'] == 3){
                $newrecordModel = new NewRecord();
                $recordData = $newrecordModel->edit($recordwhere,$record);
            }
            // 表示拆机工单
            if ($data['business_id'] == 4){
                $disassembleModel = new DisassembleRecord();
                $recordData = $disassembleModel->modifyOne($recordwhere,$record);
            }
            // 表示移机工单
            if ($data['business_id'] == 5){
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->modifyOne($recordwhere,$record);
            }
            // 表示移机拆工单
            if ($data['business_id'] == 9){
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->modifyOne($recordwhere,$record);
            }
            // 表示移机装工单
            if ($data['business_id'] == 10){
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->modifyOne($recordwhere,$record);
            }
            // 表示维修工单
            if ($data['business_id'] == 6){
                $repairModel = new RepairRecord();
                $recordData = $repairModel->edit($recordwhere,$record);
            }
            // 表示续费+维修工单
            if ($data['business_id'] == 7){
                $renewrepairModel = new RenewRepairRecord();
                $recordData = $renewrepairModel->modifyOne($recordwhere,$record);
            }
            // 表示换芯+维修工单
            if ($data['business_id'] == 8){
                $forcorerepairModel = new ForCoreRepairRecord();
                $recordData = $forcorerepairModel->modifyOne($recordwhere,$record);
            }

            // 提交事务
            Db::commit();
            $rel = true;
        }catch (\Exception $e){
            // 事务回滚
            Db::rollback();
            $rel = false;
        }

        return $rel;

    }

    /**
     * @param $where
     * @param $workOrderData
     * @param $username
     * @param $u_id
     * @return bool
     *              工单确认+指派工程部操作
     */
    public function departmentassign($where, $workOrderData, $username, $u_id, $company_name)
    {
        // 开启事务
        Db::startTrans();
        try{
            // 根据工单ID获取工单号
            $workData = $this->where($where)->find();

            // 根据条件 $where 完成一次数据修改
            $result = $this->where($where)->update($workOrderData);

            // 当为前台确认时
            if ($workOrderData['work_order_status'] == 3) {
                // 增加工单日志表记录
                $workLogData['work_order_id'] = $where['work_order_id'];          // 工单id
                $workLogData['operating_time'] = time();                          // 操作时间
                $workLogData['create_work_time'] = time();                        // 添加时间
                $workLogData['do_id'] = $u_id;                                    // 操作人id
                $workLogData['operating_type'] = 0;                               // 0为前台确认
                $workLogData['operating_status'] = 3;                             // 5为指派
                $workLogData['remarks'] = '【'.$company_name.'】管理员【'.$username.'】【管理员ID为:'.$u_id.'】已确认工单,工单号为:【'.$workData['order_number'].'】';  // 备注
                // 实例化工单日志表
                $workLogModel = new WorkOrderLog();
                // 调用add方法增加工单日志数据
                $workLogModel->add($workLogData);
            }
            // 当为指派工程部时
            if ($workOrderData['work_order_status'] == 5) {
                // 增加工单日志表记录
                $workLogData['work_order_id'] = $where['work_order_id'];          // 工单id
                $workLogData['operating_time'] = time();                          // 操作时间
                $workLogData['create_work_time'] = time();                        // 添加时间
                $workLogData['do_id'] = $u_id;                                    // 操作人id
                $workLogData['operating_type'] = 0;                               // 0为前台确认
                $workLogData['operating_status'] = 5;                             // 5为指派
                $workLogData['remarks'] = '【'.$company_name.'】管理员【'.$username.'】【管理员ID为:'.$u_id.'】指派工单给工程部,工单号为:【'.$workData['order_number'].'】';  // 备注
                // 实例化工单日志表
                $workLogModel = new WorkOrderLog();
                // 调用add方法增加工单日志数据
                $workLogModel->add($workLogData);
            }

            // 提交事务
            Db::commit();
            $rel = true;
        }catch (\Exception $e){
            // 事务回滚
            Db::rollback();
            $rel = false;
        }
        return $rel;

    }

    /**
     * @param int $id
     * @return array
     *        获取工单详情 数据
     */
    public function getDetails($id = 0) // 工单id
    {
        $data['obase']=array();
        $data['yparts']=array();
        // 获取工单详情  工单信息
        $workData = Db::table('rq_work_order')  // 工单表
        ->alias('a')
            ->join('rq_engineers b', 'b.engineers_id = a.repair_id') // 工程人员表 对应 工单表
            ->join('rq_work_equipment c', 'c.work_order_id = a.work_order_id','left') // 设备工单关联表 对应 工单表
            ->join('rq_contract_equipment ce', 'ce.id = c.contract_equipment_id','left') // 合同设备关连表 对应 设备工单关联表
            ->join('rq_equipments d', 'd.equipments_id = ce.equipments_id','left') // 设备表 对应 设备工单关联表
            ->join('rq_customer cu', 'a.user_id = cu.user_id') // 配件工单关联表 对应 工单表
            ->join('rq_contract j', 'j.contract_id = a.contract_id','left') // 合同表 对应 工单表
            ->join('rq_administrative_info h', 'h.a_id = a.administrative_id','left') // 行政中心表 对应 工单表
            ->join('rq_operation_info r', 'r.o_id = a.operation_id','left') // 运营中心表 对应 工单表
            ->field('a.work_order_id,a.service_address,a.order_number,j.contract_no,a.business_id,a.combo_money,r.company_name as y_name,h.company_name,
                                   a.work_order_status,b.engineers_name,b.engineers_phone,d.equipments_name,j.address,j.contract_id,
                                   j.for_core_cost,a.move_address,a.remarks,cu.telphone,cu.username,a.order_time,a.assigne_time')
            ->where('a.work_order_id',$id)
            ->find();
        if(!$workData){
            return false;
        }
        //处理工单类型
        $workorder_type = config('workorder_type');
        $jobtype = $workorder_type[$workData['business_id']];
        $workData['jobtype']=$jobtype;
        $data['obase'] = unsetnullArr($workData);
        $parts = Db::name('equipments_parts')->alias('ep')
            ->join('rq_parts p','ep.parts_id = p.parts_id')
            ->where(array('ep.contract_id'=>$workData['contract_id'],'ep.is_original'=>1))
            ->field('ep.id,p.parts_id,p.parts_name,ep.parts_number')
            ->select();
        $data['yparts'] = $parts;
        return $data;
    }

    /**
     * @param $workOrderData
     * @param $data
     * @param $u_id
     * @param $username
     * @return bool
     *        工单修改处理
     */
    public function modify($workOrderData, $data, $u_id, $username, $company_name)
    {
//        dump($workOrderData);echo "<hr>";
//        dump($data);die();

        // 开启事务
        Db::startTrans();
        try{

            // 判断是否新装工单修改
            if ($data['businessid'] == 3) {
                // 接受标识符并判断,1为已绑定合同,0为没有绑定合同
                if ($data['identifier'] == 1) {
                    // 先删除，在添加
                    // 实例化合同设备关联表,查询合同下面所有设备
                    $ctEqModel = new Contract();
                    $ctEqWhere['contract_id'] = $data['contract_id'];
                    $ctEqData = $ctEqModel->getEquipmentAll($ctEqWhere);

                    // 实例化工单设备关联表,删除所有设备
                    $wkEqModel = new WorkEquipment();
                    $wkEqWhere['work_order_id'] = $data['work_order_id'];
                    $wkEqRel = Db::table('rq_work_equipment')->where($wkEqWhere)->delete();
                    // 添加设备
                    foreach ($ctEqData as $k => $v)
                    {
                        // 实例化工单设备关联表
                        $wkEqModel = new WorkEquipment();
                        $wkEqData['work_order_id'] = $data['work_order_id'];
                        $wkEqData['contract_equipment_id'] = $v['id'];
                        $wkEqRel = $wkEqModel->add($wkEqData);
                    }

                }else{
                    // 判断有没有选择合同
                    if (!empty($data['contract_id'])) {
                        // 实例化合同设备关联表
                        $ctEqModel = new Contract();
                        $ctEqWhere['contract_id'] = $data['contract_id'];
                        $ctEqData = $ctEqModel->getEquipmentAll($ctEqWhere);
                        foreach ($ctEqData as $k => $v)
                        {
                            // 实例化工单设备关联表
                            $wkEqModel = new WorkEquipment();
                            $wkEqData['work_order_id'] = $data['work_order_id'];
                            $wkEqData['contract_equipment_id'] = $v['id'];
                            $wkEqRel = $wkEqModel->add($wkEqData);
                        }
                    }
                }
            }else{
                // 当业务类型不是新装时
                if (!empty($data['equipmentsname'])) {
                    // 实例化工单设备关联表 完成一次修改
                    $wkEqModel = new WorkEquipment();
                    $wkEqWhere['work_order_id'] = $data['work_order_id'];
                    $wkEqData['contract_equipment_id'] = $data['equipmentsname'];
                    $wkEqModel->edit($wkEqWhere, $wkEqData);
                }
            }

            $workwhere['work_order_id'] = $data['work_order_id'];

            // 根据工单ID，获取工单号
            $workData = $this->where($workwhere)->find();
            // 根据条件 $where 完成一次工单数据修改
            $result = $this->where($workwhere)->update($workOrderData);


            // 当修改业务类型不为新装时，修改工单设备关联表
            if (!$data['businessid'] == 3) {
                // 实例化工单设备关联表 对它完成一次修改
                $workEquipmentModel = new WorkEquipment();
                $eqwhere['work_order_id'] = $data['work_order_id'];             // 工单ID
                $eqData['contract_equipment_id'] = $data['equipmentsname'];     // 合同设备关联ID
                $eqRel = $workEquipmentModel->edit($eqwhere,$eqData);
            }


            // 增加工单日志表记录
            $workLogData['work_order_id'] = $data['work_order_id'];            // 工单id
            $workLogData['operating_time'] = time();                           // 操作时间
            $workLogData['create_work_time'] = time();                           // 操作时间
            $workLogData['do_id'] = $u_id;                                     // 操作人id
            $workLogData['operating_type'] = 3;                                // 0为前台确认
            $workLogData['operating_status'] = 15;                             // 5为指派
            $workLogData['remarks'] = '【'.$company_name.'】管理员【'.$username.'】【管理员ID为:'.$u_id.'】修改了工单内容,工单号为:【'.$workData['order_number'].'】';  // 备注
            // 实例化工单日志表
            $workLogModel = new WorkOrderLog();
            // 调用add方法增加工单日志数据
            $logRel = $workLogModel->add($workLogData);

            // 提交事务
            Db::commit();
            $rel = true;
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            $rel = false;
        }

        return $rel;

    }



}